import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/commom/Dio.dart';
import 'package:flutter_app/commom/Global.dart';
import 'package:flutter_app/models/creatProject.dart';
import 'package:flutter_app/models/ganttChart.dart';
import 'package:flutter_app/widgets/ReleasePjResultCard.dart';
import 'package:unicorndial/unicorndial.dart';
import 'GanttRoute.dart';
import 'ReleasePdRoute.dart';

class ProjectEdit extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ProjectEditState();
  }
}

class ProjectEditState extends State<ProjectEdit> {
  int floatingButton = 0;
  int projectId = 0;
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
  TextEditingController newName = TextEditingController();
  TextEditingController newExp = TextEditingController();
  bool data_value = true;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  void initState() {
    Global.creatProject = CreatProject();
    Global.creatProject.pd = List();
    Global.usersInChart = List();
    Global.dataInChart = List();
    if (Global.creatProject.pjProtime == null ||
        Global.creatProject.pjDeltime == null) data_value = false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      backgroundColor: Colors.white,
      appBar: AppBar(
          backgroundColor: Colors.white,
          centerTitle: true,
          title: Text('发布需求',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontSize: 20.0,
                height: 1.2,
              )),
          actions: <Widget>[
            Padding(
                padding: new EdgeInsets.only(),
                child: new FlatButton(
                  child: Text(
                    "提交",
                    style: TextStyle(
                      color: Colors.black,
                      fontSize: 15,
                    ),
                  ),
                  onPressed: () => ({
                      _onUploadPj()
                  }),
                )
              //导航栏右侧菜单
            )
          ],
          elevation: 0, //去掉Appbar底部阴影
          brightness: Brightness.light, //状态栏颜色

          leading: Builder(builder: (context) {
            return new IconButton(
              icon: new Icon(
                Icons.arrow_back_ios,
                color: Colors.grey,
              ),
              tooltip: '退出',
              onPressed: () => ({
                Navigator.of(context).pop()
              }),
            );
          })),
      floatingActionButton: UnicornDialer(
        parentButtonBackground: Colors.black12,
        orientation: UnicornOrientation.VERTICAL,
        parentButton: Icon(
            Icons.arrow_drop_up,
            color: Colors.black26,
            size: 4,
        ),
        childButtons: getAddMenu(),
      ),
      body: Theme(
        data: new ThemeData(
          primaryColor: Colors.black45,
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            //注：
            Padding(
              padding: EdgeInsets.only(left: 20.0, top: 20),
              child: Text(
                "在发布需求之前请先确认您已完善个人信息",
                style: TextStyle(
                  color: Colors.grey,
                  fontSize: 14.0,
                  //background: new Paint()..color = Colors.yellow,
                ),
              ),
            ),
            Form(
              key: _formKey,
              //项目名称
              child: Padding(
                  padding: EdgeInsets.only(left: 20.0, top: 20),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "请输入项目名称",
                        style: TextStyle(
                          color: Colors.black87,
                          fontSize: 14.0,
                          //background: new Paint()..color = Colors.yellow,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(right: 20.0, top: 10),
                        child: TextFormField(
                          autofocus: false,
                          controller: newName,
                          style: TextStyle(
                            fontSize: 15,
                          ),
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.only(left: 10.0),
                            hintText: Global.creatProject.pjName,
                            hintStyle: new TextStyle(
                              color: Colors.grey,
                              fontSize: 15,
                            ),
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5.0),
                                borderSide: BorderSide()),
                          ),
                          validator: (value) {
                            if (value.isEmpty && Global.creatProject.pjName == null) {
                              return '请输入工程订单名称';
                            }
                            else if(value.isNotEmpty) Global.creatProject.pjName = value;
                            return null;
                          },
                        ),
                      )
                    ],
                  )),
            ),
            //开始时间
            Padding(
                padding: EdgeInsets.only(left: 20.0, top: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "请设置开始日期",
                      style: TextStyle(
                        color: Colors.black87,
                        fontSize: 14.0,
                        //background: new Paint()..color = Colors.yellow,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(right: 20.0, top: 10),
                      child: TextField(
                        enableInteractiveSelection: false,
                        onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); },
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.only(left: 10.0),
                          hintText: Global.creatProject.pjProtime == null ?
                          formatDate(DateTime.now(), [yyyy, '-', mm, '-', d, ' ', HH, ':', nn, ':', ss])
                              : formatDate(Global.creatProject.pjProtime, [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]),
                          hintStyle: new TextStyle(
                            color: Colors.grey,
                            fontSize: 15,
                          ),
                          suffixIcon: IconButton(
                            icon: new Icon(
                              Icons.calendar_today_rounded,
                              color: Colors.grey,
                            ),
                            onPressed: () async {
                              var result = await showDatePicker(
                                context: context,
                                //locale: Locale('zh'),
                                initialDate: DateTime.now(),
                                selectableDayPredicate: (DateTime day) {
                                  return day
                                      .difference(DateTime.now())
                                      .inDays < 365;
                                },
                                firstDate: DateTime.now(),
                                lastDate: DateTime(2023),
                                builder: (context, child) {
                                  return Theme(
                                    data: ThemeData.from(
                                        colorScheme: ColorScheme
                                            .highContrastLight()),
                                    child: child,
                                  );
                                },
                              );
                              setState(() {
                                if (result == null && Global.creatProject.pjProtime == null)  data_value = false;
                                else {
                                  Global.creatProject.pjProtime = result;
                                  data_value = true;
                                }
                              });
                            },
                          ),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0),
                              borderSide: BorderSide()),
                        ),
                      ),
                    )
                  ],
                )),
            //截止日期
            Padding(
                padding: EdgeInsets.only(left: 20.0, top: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "请设置截止日期",
                      style: TextStyle(
                        color: Colors.black87,
                        fontSize: 14.0,
                        //background: new Paint()..color = Colors.yellow,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(right: 20.0, top: 10),
                      child: TextField(
                        enableInteractiveSelection: false,
                        onTap: () { FocusScope.of(context).requestFocus(new FocusNode()); },
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.only(left: 10.0),
                          hintText: Global.creatProject.pjDeltime == null ?
                          formatDate(DateTime.now(), [yyyy, '-', mm, '-', d, ' ', HH, ':', nn, ':', ss])
                              : formatDate(Global.creatProject.pjDeltime, [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ':', ss]),
                          hintStyle: new TextStyle(
                            color: Colors.grey,
                            fontSize: 15,
                          ),
                          suffixIcon: IconButton(
                            icon: new Icon(
                              Icons.calendar_today_rounded,
                              color: Colors.grey,
                            ),
                            onPressed: () async {
                              var result = await showDatePicker(
                                context: context,
                                //locale: Locale('zh'),
                                initialDate: Global.creatProject.pjProtime == null ? DateTime.now() : Global.creatProject.pjProtime,
                                selectableDayPredicate: (DateTime day) {
                                  return day
                                      .difference(DateTime.now())
                                      .inDays < 365;
                                },
                                firstDate: Global.creatProject.pjProtime == null ? DateTime.now() : Global.creatProject.pjProtime,
                                lastDate: DateTime(2023),
                                builder: (context, child) {
                                  return Theme(
                                    data: ThemeData.from(
                                        colorScheme: ColorScheme
                                            .highContrastLight()),
                                    child: child,
                                  );
                                },
                              );
                              setState(() {
                                if(result == null && Global.creatProject.pjDeltime == null)
                                  data_value = false ;
                                else {
                                  //if(data_value == true)data_value = true;
                                  Global.creatProject.pjDeltime= result;
                                }
                              });
                            },
                          ),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0),
                              borderSide: BorderSide()),
                        ),
                      ),
                    )
                  ],
                )),
            //备注
            Padding(
                padding: EdgeInsets.only(left: 20.0, top: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "请输入项目说明",
                      style: TextStyle(
                        color: Colors.black87,
                        fontSize: 14.0,
                        //background: new Paint()..color = Colors.yellow,
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(right: 20.0, top: 10),
                      child: TextField(
                        autofocus: false,
                        controller: newExp,
                        maxLines: 3,
                        style: TextStyle(
                          fontSize: 15,
                        ),
                        //controller: name,
                        //inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],//只允许输入数字
                        decoration: InputDecoration(
                          contentPadding: EdgeInsets.only(left: 10.0, top: 20),
                          hintText: " 输入项目说明",
                          hintStyle: new TextStyle(
                            color: Colors.grey,
                            fontSize: 13,
                          ),
                          border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(5.0),
                              borderSide: BorderSide()),
                        ),
                        onSubmitted:(val){
                          Global.creatProject.pjNote = val;
                        },
                      ),
                    )
                  ],
                )),
            //编辑工序
            Padding(
                padding: EdgeInsets.only(left: 20.0, top: 10),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "请编辑项目工序信息（点击‘+’以增加工序并编辑）",
                      style: TextStyle(
                        color: Colors.black87,
                        fontSize: 14.0,
                        //background: new Paint()..color = Colors.yellow,
                      ),
                    ),
                    Padding(
                        padding: EdgeInsets.only(top: 10),
                        child: Wrap(
                          children: [
                            Wrap(
                              spacing: 1.0,
                              children: List.generate(Global.creatProject.pd.length, (index) {
                                return Container(
                                  constraints: BoxConstraints(
                                    maxWidth: 70,
                                    maxHeight: 70,
                                  ),
                                  child: Builder(
                                    builder: (context) =>RaisedButton(
                                      onPressed: () => {
                                        _onReleasePdRoute(context, index)
                                      },
                                      color: Colors.white,
                                      child: Text((index + 1).toString()),
                                      shape: CircleBorder(),
                                    ),
                                  )

                                );
                              }),
                            ),
                          ],
                        ))
                  ],
                )),
          ],
        ),
      ),
      resizeToAvoidBottomPadding: false,
    );
  }
  List<UnicornButton> getAddMenu() {
    List<UnicornButton> children = [];
    // Add Children here
    children.add(_addOption(
        iconData: Icons.add,
        onPressed: (){
          setState(() {
            Global.creatProject.pd.add(
              {
                "pdName": " ",
                "pdDemand": " ",
                //"pdProtime": DateTime.now(),
                //"pdDeltime": DateTime.now(),
                "bsIds": []
              },
            );
          });
        },
        index:floatingButton,
        ));
    children.add(
        _addOption(
            iconData: Icons.bar_chart,
            onPressed:() {
              _onGanttChart(context);
            }
        ));
    return children;
  }
  Widget _addOption({IconData iconData, Function onPressed,int index}) {
    return UnicornButton(
        currentButton: FloatingActionButton(
          backgroundColor: Colors.black54,
          mini: true,
          child: Icon(iconData),
          onPressed: onPressed,
          heroTag: index,
        )
    );
  }

  void _onGanttChart(BuildContext context){
    if(Global.creatProject.pd.isEmpty){
      scaffoldKey.currentState.showSnackBar(SnackBar(content: Text('先创建工序后才可以预览甘特图哦')));
    }
    else {
      Global.usersInChart = List();
      Global.dataInChart = List();
      Global.creatProject.pd.forEach((element) {
        Global.dataInChart.add(
            Project(
                id:projectId,
                name:element['pdName'],
                startTime:element['pdProtime'],
                endTime: element['pdDeltime'],
                participants: [0]
            )
        );
        projectId = projectId + 1;
      });
      Global.usersInChart.add(
          User(
              id: 0,
              name: ''
          )
      );
      Navigator.push(
        context,
        new MaterialPageRoute(builder: (context) {
          return new GanttChartScreen(
              projects:Global.dataInChart,
              users:Global.usersInChart,
              title:"甘特图发布预览",
              fromDate: Global.creatProject.pjProtime,
              toDate: Global.creatProject.pjDeltime,
          );
        }),
      );
    }
  }
  void _onReleasePdRoute(BuildContext context, int index){
    if(Global.creatProject.pjProtime == null || Global.creatProject.pjDeltime == null)
      data_value = false;
    if(_formKey.currentState.validate() && data_value){
      if(Global.creatProject.pjDeltime.isAfter(Global.creatProject.pjProtime)){
        Navigator.push(
          context,
          new MaterialPageRoute(builder: (context) {
            return new ReleasePdRoute(
                pd_Index: index
            );
          }),
        );
      }
      else Scaffold.of(context).showSnackBar(SnackBar(content: Text('您还有信息没有完善哟')));
    }
    //else if(Global.creatProject.pjDeltime.isBefore(Global.creatProject.pjDeltime))
      //Scaffold.of(context).showSnackBar(SnackBar(content: Text('日期设置不正确哦')));
    else Scaffold.of(context).showSnackBar(SnackBar(content: Text('您还有信息没有完善哟')));
  }

  void _onUploadPj()async{

    int status = await EA(context).releaseProject();
    if(status == 200){
      await ReleaseSuccessedCard(context);
      Navigator.of(context).pop();
    }
    else await ReleaseFailedCard(context);

  }

}